package com.hsmw.api.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hsmw.api.mapper.*;
import com.hsmw.api.vo.*;
import com.hsmw.common.base.BaseService;
import com.htn.common.core.base.DataResponse;
import com.htn.common.core.constant.CommonConstants;
import com.htn.common.core.constant.CorperateTypeEnum;
import com.htn.common.core.constant.HtnUserTypeEnum;
import com.htn.common.core.utils.StringUtils;
import com.hsmw.domain.*;
import com.hsmw.domain.vo.VehicleInfoVO;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import static com.htn.common.core.constant.CommonConstants.ResponseStatus.FAIL;


/**
 * @author WD
 */
@Service
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class HsmwVehicleService extends BaseService<HsmwVehicleMapper, HsmwVehicle> {

	@Autowired
	private HsmwVehicleMapper hsmwVehicleMapper;
	@Autowired
	private HsmwLeasingCompanyMapper hsmwLeasingCompanyMapper;


	@Autowired
	private HsmwUserDriverService hsmwUserDriverService;

	@Autowired
	private HsmwOrderMapper hsmwOrderMapper;

	@Autowired
	private HsmwHtnUserService hsmwHtnUserService;


	@Autowired
	private HsmwCorporationCompanyMapper hsmwCorporationCompanyMapper;

	@Autowired
	private HsmwOrderVehicleRelationService hsmwOrderVehicleRelationService;


	public IPage<HsmwVehicle> getVehiclePage(IPage page, HsmwVehicle hsmwVehicle) {
		LambdaQueryWrapper<HsmwVehicle> queryWrapper = new LambdaQueryWrapper<>();
		if(hsmwVehicle != null){
			if (StrUtil.isNotBlank(hsmwVehicle.getLeasingCompanyId())) {
				queryWrapper.eq(HsmwVehicle::getLeasingCompanyId, hsmwVehicle.getLeasingCompanyId());
			}
			if (StrUtil.isNotBlank(hsmwVehicle.getVehiclePlate())) {
				queryWrapper.like(HsmwVehicle::getVehiclePlate, hsmwVehicle.getVehiclePlate());
			}
			if (StrUtil.isNotBlank(hsmwVehicle.getLeasingCompanyType())) {
				queryWrapper.eq(HsmwVehicle::getLeasingCompanyType, hsmwVehicle.getLeasingCompanyType());
			}
			if (StrUtil.isNotBlank(hsmwVehicle.getVehicleType())) {
				queryWrapper.eq(HsmwVehicle::getVehicleType, hsmwVehicle.getVehicleType());
			}
			if (StrUtil.isNotBlank(hsmwVehicle.getVehicleModel())) {
				queryWrapper.like(HsmwVehicle::getVehicleModel, hsmwVehicle.getVehicleModel());
			}
			if (StrUtil.isNotBlank(hsmwVehicle.getWorkStatus())) {
				queryWrapper.eq(HsmwVehicle::getWorkStatus, hsmwVehicle.getWorkStatus());
			}
			queryWrapper.orderByAsc(HsmwVehicle::getWorkStatus);
		}
		return hsmwVehicleMapper.selectPage(page, queryWrapper);
	}

	public HsmwVehicle getVehicleById(String id) {
		LambdaQueryWrapper<HsmwVehicle> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(HsmwVehicle::getId, id);
		return hsmwVehicleMapper.selectOne(queryWrapper);
	}

	public int saveOrUpdateVehicle(HsmwVehicle hsmwVehicle) {
		int result;
		if (StrUtil.isBlank(hsmwVehicle.getId())) {
			//TODO 车牌号查重
			String vehiclePlate = hsmwVehicle.getVehiclePlate();
			HsmwLeasingCompany hsmwLeasingCompany = hsmwLeasingCompanyMapper.selectById(hsmwVehicle.getLeasingCompanyId());
			hsmwVehicle.setLeasingCompanyName(hsmwLeasingCompany.getName());
			hsmwVehicle.setWorkStatus(CommonConstants.VEHICLE_FREE);
			hsmwVehicle.setFlag(0);
			// TODO 新增车辆信息时 缺少租赁公司类型 租赁公司表中缺少类型字段
			hsmwVehicle.setLeasingCompanyType("自营");
			result = hsmwVehicleMapper.insert(hsmwVehicle);
		} else {
			HsmwLeasingCompany hsmwLeasingCompany = hsmwLeasingCompanyMapper.selectById(hsmwVehicle.getLeasingCompanyId());
			if(hsmwLeasingCompany != null){
				hsmwVehicle.setLeasingCompanyName(hsmwLeasingCompany.getName());
			}
			HashMap param = new HashMap();
			param.put("vehicleId", hsmwVehicle.getId());
			List<CurrentOrderInfoVO> orderList = hsmwOrderVehicleRelationService.getGoingOrderListByParam(param);
			if(hsmwVehicle.getDrivingLicenseTime().isAfter(LocalDate.now()) && hsmwVehicle.getCommercialInsuranceTime().isAfter(LocalDate.now()) && hsmwVehicle.getCompuTrafficTime().isAfter(LocalDate.now())){
				if(CollectionUtil.isEmpty(orderList)){
					hsmwVehicle.setWorkStatus(CommonConstants.VEHICLE_FREE);
				}else {
					hsmwVehicle.setWorkStatus(CommonConstants.VEHICLE_WORK);
				}
			}
			result = hsmwVehicleMapper.updateById(hsmwVehicle);
		}
		return result;
	}


	public List<HsmwVehicle> getDriverVehicleSelect() {
		return hsmwVehicleMapper.getDriverVehicleSelect();
	}

	public ManageVehicleListVo getManageVehicleList(String leasingCompanyId) {
		List<HsmwVehicle> noChooseLeasingCompanyList = hsmwVehicleMapper.selectList(Wrappers.lambdaQuery(HsmwVehicle.class).isNull(HsmwVehicle::getLeasingCompanyId));
		List<HsmwVehicle> chooseLeasingCompanyList = hsmwVehicleMapper.selectList(Wrappers.lambdaQuery(HsmwVehicle.class).eq(HsmwVehicle::getLeasingCompanyId, leasingCompanyId));
		noChooseLeasingCompanyList.addAll(chooseLeasingCompanyList);
		return ManageVehicleListVo.builder().noChooseList(noChooseLeasingCompanyList).chooseList(chooseLeasingCompanyList).build();
	}

	public IPage<VehicleDataCollectVO> getVehicleDataCollect(IPage page, VehicleDataCollectVO requestData) {
		return hsmwVehicleMapper.getVehicleDataCollect(page, requestData);
	}

	public void updateMobileLocation(HashMap param){
		hsmwVehicleMapper.updateMobileLocation(param);

	}

	@Transactional
    public DataResponse tranfervehicle(VehicleTranferVO vehicleTranferVO) {
		//校验有没有工作中的司机朋友
		List<HsmwUserDriver> drivers = new ArrayList<>();
		if(StringUtils.isNotBlank(vehicleTranferVO.getDriverIds())){
			String[] driverIds = vehicleTranferVO.getDriverIds().split(",");
			List<String> ids = Arrays.asList(driverIds);
			drivers =hsmwUserDriverService.listByIds(ids);
			for(HsmwUserDriver driver :drivers){
				if(StringUtils.isNotBlank(driver.getWorkStatus()) && CommonConstants.DRIVER_WORK.equals(driver.getWorkStatus())){
					return DataResponse.failure(CommonConstants.ResponseStatus.FAIL.getCode(),"您选择的司机"+driver.getId()+"正在工作中不能进行转移，请重新选择！");
				}
				break;
			}
		}
		//首先将该车辆的所有的司机都置为空
		HashMap param  =new HashMap();
		param.put("vehicleId",vehicleTranferVO.getVehicleId());
		hsmwUserDriverService.resetVehicleBindDrivers(param);
		//然后将选择的司机的车辆改为 所选的车辆
		if (CollectionUtil.isNotEmpty(drivers)){
			drivers.stream().forEach(driver->{
				driver.setVehicleId(vehicleTranferVO.getVehicleId());
			});
			hsmwUserDriverService.saveOrUpdateBatch(drivers);
		}
		return new DataResponse();
    }

    public List<IdleVehicleVo> findVehicleList(QueryFreeParams queryFreeParams) {

		return hsmwVehicleMapper.findVehicleList(queryFreeParams);
	}

    public  List<HsmwVehicle> selectPlateformVehicles(HashMap param) {
		return hsmwVehicleMapper.selectPlateformVehicles(param);
    }


	public  List<HsmwVehicle> selectForemanPlateformVehicles(HashMap param) {
		return hsmwVehicleMapper.selectForemanPlateformVehicles(param);
	}

	public  List<HsmwVehicle> checkIfPlateformVehicles(HashMap param) {
		return hsmwVehicleMapper.checkIfPlateformVehicles(param);
	}
}
